<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工单编号" prop="orderNumber">
        <el-input v-model="queryParams.orderNumber" placeholder="请输入工单编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="任务专业" prop="taskType">
        <el-select v-model="queryParams.taskType" placeholder="请选择任务专业" clearable>
          <el-option v-for="dict in dict.type.insp_task_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="区段" prop="section">
        <el-select v-model="queryParams.section" placeholder="请选择区段" clearable>
          <el-option label="K123+100-K124+100" value="K123+100-K124+100" />
          <el-option label="K223+100-K224+100" value="K223+100-K224+100" />
          <el-option label="K323+100-K324+100" value="K323+100-K324+100" />
          <el-option label="K423+100-K424+100" value="K423+100-K424+100" />
          <el-option label="K523+100-K524+100" value="K523+100-K524+100" />
          <el-option label="K623+100-K624+100" value="K623+100-K624+100" />
          <el-option label="K723+100-K724+100" value="K723+100-K724+100" />
          <el-option label="K300+200-K324+200" value="K300+200-K324+200" />
          <el-option label="K600+200-K624+200" value="K600+200-K624+200" />
        </el-select>
      </el-form-item>
      <el-form-item label="平台" prop="platform">
        <el-select v-model="queryParams.platform" placeholder="请选择平台" clearable>
          <el-option v-for="dict in dict.type.insp_task_platform" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" prop="taskStartTime">
        <el-date-picker clearable v-model="queryParams.taskStartTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择作业开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="taskEndTime">
        <el-date-picker clearable v-model="queryParams.taskEndTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择作业结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['inspection:task:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['inspection:task:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['inspection:task:remove']">删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['inspection:task:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-data-analysis" size="mini" :disabled="single"
          @click="handleDefect">缺陷检测</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键id" align="center" prop="id" />
      <el-table-column label="工单编号" align="center" prop="orderNumber" />
      <el-table-column label="任务专业" align="center" prop="taskType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.insp_task_type" :value="scope.row.taskType" />
        </template>
      </el-table-column>
      <el-table-column label="区段" align="center" prop="section" />
      <el-table-column label="平台" align="center" prop="platform">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.insp_task_platform" :value="scope.row.platform" />
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="taskStartTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.taskStartTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="taskEndTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.taskEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采集" align="center" prop="gather" />
      <el-table-column label="检查" align="center" prop="inspect" />
      <el-table-column label="处理" align="center" prop="dealWith" />
      <el-table-column label="复核" align="center" prop="review" />
      <el-table-column label="报告" align="center" prop="report" />
      <el-table-column label="检修" align="center" prop="maintenance" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleReport(scope.row)">查看报告</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['inspection:task:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['inspection:task:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改巡检任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="工单编号" prop="orderNumber">
          <el-input v-model="form.orderNumber" placeholder="请输入工单编号" />
        </el-form-item> -->
        <el-form-item label="任务专业" prop="taskType">
          <el-select v-model="form.taskType" placeholder="请选择任务专业">
            <el-option v-for="dict in dict.type.insp_task_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区段" prop="section">
          <el-select v-model="form.section" placeholder="请选择区段">
            <el-option label="K123+100-K124+100" value="K123+100-K124+100" />
            <el-option label="K223+100-K224+100" value="K223+100-K224+100" />
            <el-option label="K323+100-K324+100" value="K323+100-K324+100" />
            <el-option label="K423+100-K424+100" value="K423+100-K424+100" />
            <el-option label="K523+100-K524+100" value="K523+100-K524+100" />
            <el-option label="K623+100-K624+100" value="K623+100-K624+100" />
            <el-option label="K723+100-K724+100" value="K723+100-K724+100" />
            <el-option label="K300+200-K324+200" value="K300+200-K324+200" />
            <el-option label="K600+200-K624+200" value="K600+200-K624+200" />
          </el-select>
        </el-form-item>
        <el-form-item label="平台" prop="platform">
          <el-select v-model="form.platform" placeholder="请选择平台">
            <el-option v-for="dict in dict.type.insp_task_platform" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="taskStartTime">
          <el-date-picker clearable v-model="form.taskStartTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择作业开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="taskEndTime">
          <el-date-picker clearable v-model="form.taskEndTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择作业结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="采集" prop="gather">
          <el-input v-model="form.gather" placeholder="请输入采集" />
        </el-form-item>
        <el-form-item label="检查" prop="inspect">
          <el-input v-model="form.inspect" placeholder="请输入检查" />
        </el-form-item>
        <el-form-item label="处理" prop="dealWith">
          <el-input v-model="form.dealWith" placeholder="请输入处理" />
        </el-form-item>
        <el-form-item label="复核" prop="review">
          <el-input v-model="form.review" placeholder="请输入复核" />
        </el-form-item>
        <el-form-item label="报告" prop="report">
          <el-input v-model="form.report" placeholder="请输入报告" />
        </el-form-item>
        <el-form-item label="检修" prop="maintenance">
          <el-input v-model="form.maintenance" placeholder="请输入检修" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 弹窗 -->
    <el-dialog title="查看工单" :visible.sync="dialogVisible" width="50%">
      <div class="task-details">
        <!-- 表格内容 -->
        <div class="details-grid">
          <el-row class="row">
            <el-col :span="6" class="label">工单编号</el-col>
            <el-col :span="18" class="value">{{ form.orderNumber }}</el-col>
          </el-row>
          <el-row class="row">
            <el-col :span="6" class="label">任务专业</el-col>
            <el-col :span="18" class="value">
              <dict-tag :options="dict.type.insp_task_type" :value="form.taskType" />
            </el-col>
          </el-row>
          <el-row class="row">
            <el-col :span="6" class="label">巡检区段</el-col>
            <el-col :span="18" class="value">{{ form.section }}</el-col>
          </el-row>
          <el-row class="row">
            <el-col :span="6" class="label">作业平台</el-col>
            <el-col :span="18" class="value">
              <dict-tag :options="dict.type.insp_task_platform" :value="form.platform" />
            </el-col>
          </el-row>
          <el-row class="row">
            <el-col :span="6" class="label">巡检时间</el-col>
            <el-col :span="18" class="value">{{ form.taskStartTime }} - {{ form.taskEndTime }}</el-col>
          </el-row>
          <el-row class="row">
            <el-col :span="6" class="label">作业规范</el-col>
            <el-col :span="18" class="value">
              GD2024.1新朔铁路供电系统无人机巡检作业规范
              {{ form.specifications }}</el-col>
          </el-row>
          <el-row class="row">
            <el-col :span="6" class="label">检查结果</el-col>
            <el-col :span="18" class="value">{{ form.inspect }}</el-col>
          </el-row>
          <el-row class="row">
            <el-col :span="6" class="label">识别结果</el-col>
            <el-col :span="18" class="value">
              识别缺陷图片：{{ detectResults.length > 0 ? detectResults.length : '0' }}张。
              <span v-if="detectResults && detectResults.length > 0" v-for="(object, index) in detectResults"
                :key="index">
                <el-link type="primary" @click="drawImageWithBboxes(object)">{{ object.name }}</el-link>
                <span v-if="index < detectResults.length - 1">，</span>
              </span>
            </el-col>
          </el-row>
          <el-row class="row">
            <el-col :span="6" class="label">复核结果</el-col>
            <el-col :span="18" class="value">{{ form.review }}</el-col>
          </el-row>
        </div>
      </div>
      <!-- 弹窗操作按钮 -->
      <template #footer>
        <el-button @click="handleExportReport(form.id)">导出报告</el-button>
        <el-button @click="dialogVisible = false">返回</el-button>
      </template>
      <el-dialog title="识别结果" :visible.sync="reportVisible" width="50%" center append-to-body>
        <canvas class="canvas" ref="canvas" :width="canvasWidth" :height="canvasHeight"></canvas>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import { listTask, getTask, delTask, addTask, updateTask, getDetectResults } from "@/api/inspection/task";
import { detect } from "@/api/third_api";
//导入axios
// import axios from 'axios';
import { MessageBox } from 'element-ui';

export default {
  name: "Task",
  dicts: ['insp_task_type', 'insp_task_platform'],
  data() {
    return {
      canvasWidth: 600, // Canvas 的宽度
      canvasHeight: 500, // Canvas 的高度
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 巡检任务表格数据
      taskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNumber: null,
        taskType: null,
        section: null,
        platform: null,
        taskStartTime: null,
        taskEndTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      dialogVisible: false,
      reportVisible: false,
      //报告返回体
      detectResults: [],
    };
  },
  created() {
    this.getList();
  },

  methods: {
    drawImageWithBboxes(object) {
      this.reportVisible = true;
      this.$nextTick(() => {
        const canvas = this.$refs.canvas;
        const ctx = canvas.getContext("2d");
        // 加载图片
        const img = new Image();
        img.src = object.base64Img;
        img.onload = () => {
          // 按比例缩放图片以适配 canvas 尺寸
          const scaleX = this.canvasWidth / img.width;
          const scaleY = this.canvasHeight / img.height;
          const scale = Math.min(scaleX, scaleY);

          // 计算图片绘制的起点（居中显示）
          const offsetX = (this.canvasWidth - img.width * scale) / 2;
          const offsetY = (this.canvasHeight - img.height * scale) / 2;

          // 绘制图片
          ctx.drawImage(
            img,
            offsetX,
            offsetY,
            img.width * scale,
            img.height * scale
          );
          // 绘制矩形框
          //bbox 的格式 [x_min, y_min, x_max, y_max]
          // this.bboxes.forEach((item) => {
          const [xMin, yMin, xMax, yMax] = object.bbox;
          const rectX = xMin * scale + offsetX;
          const rectY = yMin * scale + offsetY;
          const rectWidth = (xMax - xMin) * scale;
          const rectHeight = (yMax - yMin) * scale;
          // 绘制矩形框
          ctx.beginPath();
          // ctx.strokeStyle = item.color;
          ctx.strokeStyle = 'red';
          ctx.lineWidth = 2;
          ctx.rect(rectX, rectY, rectWidth, rectHeight);
          ctx.stroke();
          // });
        };
      });
    },
    /** 查询巡检任务列表 */
    getList() {
      this.loading = true;
      listTask(this.queryParams).then(response => {
        this.taskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderNumber: null,
        taskType: null,
        section: null,
        platform: null,
        specifications: "GD2024.1 新朔铁路供电系统无人机巡检作业规范",
        taskStartTime: null,
        taskEndTime: null,
        gather: null,
        inspect: null,
        dealWith: null,
        review: null,
        report: null,
        maintenance: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    //查看工单报告 detect
    handleReport(row) {
      this.dialogVisible = true
      this.form = row;
      const orderNumber = row.orderNumber;
      const data = {
        "orderNumber": orderNumber,
        "sourceUrl": "/home/wurenhua/mov_bbb.mp4"
      }
      getDetectResults(data).then((res) => {
        console.log(res);
        if (res.code === 200) {
          this.detectResults = res.data;
        } else {
          MessageBox.alert("查询检测结果失败", '报告提示', { dangerouslyUseHTMLString: true, type: 'error' });
        }
      }).catch(function (error) { // 请求失败处理
        MessageBox.alert(error, '异常提示', { type: 'error' });
        console.log(error);
      });

    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加巡检任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTask(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改巡检任务";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTask(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTask(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除巡检任务编号为"' + ids + '"的数据项？').then(function () {
        return delTask(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('inspection/task/export', {
        ...this.queryParams
      }, `task_${new Date().getTime()}.xlsx`)
    },

    /** 缺陷检测按钮操作 */
    handleDefect(row) {
      const id = row.id || this.ids[0];
      const data = {
        "id": id,
      }
      this.$modal.confirm('是否确认进行缺陷检测？').then(function () {
        detect(data).then((res) => {
          console.log(res);
          if (res.code === 200) {
            if (res.data.code == 200) {
              MessageBox.alert(res.data.msg, '检测提示', { dangerouslyUseHTMLString: true, type: 'success' });
            } else {
              MessageBox.alert("<span>请求参数：" + JSON.stringify(res.data.msg.request) + "</span>" + "<br/><span>返回参数：" + JSON.stringify(res.data.msg.response) + "</span>", '报告提示', { dangerouslyUseHTMLString: true, type: 'error' });
            }
          } else {
            MessageBox.alert(res.msg, '错误提示', { dangerouslyUseHTMLString: true, type: 'error' });
          }
        }).catch(() => {
          MessageBox.alert(error, '异常提示', { type: 'error' });
        });
      }).catch(() => {
        MessageBox.alert(error, '异常提示', { type: 'error' });
      });
    },
    /** 导出报告按钮操作 */
    handleExportReport(id) {
      this.download('inspection/task/exportReport', {
        "id": id
      }, `report_${new Date().getTime()}.pdf`)
    }
  }
};
</script>

<style scoped>
::v-deep .el-dialog__body {
  padding: 5px 20px;
}

::v-deep .el-dialog__header {
  background-color: rgb(0, 0, 255);
  color: white;

  .el-dialog__title {
    color: white;
  }

  .el-dialog__headerbtn .el-dialog__close {
    color: white;
  }
}


.task-details {
  display: flex;
  flex-direction: column;
}

/* 自定义网格样式 */
.details-grid {
  margin-bottom: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  overflow: hidden;
}

.details-grid .row {
  display: flex;
  border-bottom: 1px solid #ccc;
}

.details-grid .row:last-child {
  border-bottom: none;
}

.details-grid .label {
  background-color: #f4f6ff;
  font-weight: bold;
  padding: 10px;
  border-right: 1px solid #ccc;
}

.details-grid .value {
  padding: 10px;
}

/* 地图样式 */
.map-container {
  text-align: center;
  margin-top: 20px;
}

.map-container img {
  max-width: 100%;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.canvas {
  display: block;
  margin: auto;
  border: 1px solid rgb(162, 162, 162);
  border-radius: 16px;
}
</style>